<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Controllers;

use Sun\Sun;
use Sun\Validators;
use App\Models;

class Index extends \Sun\Controller {
    public function __construct() {
        parent::__construct("Main");
    }

    public function MainAction($req) {
        if (isset($req->data['p'])){
            $v = $req->data['p'];
            $this->RenderView($v, $req->data);
        } else if (isset($req->data['m'])) {
            $v = $req->data['m'];
            $this->RenderViewScene($v, $req->data);
        } else {
            $this->RenderView("Index\\Main", $req->data);
        }
    }

    public function LoginAction($req) {
        if ($req->method == "GET")
            header("Location: ?p=Index\\Enter");

        $validator = new Validators\ArrayValidator(
            new Validators\NullValidator());
        $res = new \Sun\Response();

        try {
            if (!$validator->Verify($req->data)) throw new \Sun\Exception("", 1);

            $auth = new Models\Session();

            if (!$auth->Login($req->data)) throw new \Sun\Exception("", 2);
            $profile = $auth->Profile();
            if (strtotime($profile['reg_comp']) < time())
                throw new \Sun\Exception("", 3);

            $res->STAT = 'OK';
            $res->URL = '?p=Index\\Enter';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';
            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $validator->Exceptions();
                    break;
                case 2:
                    $res->ERR = array('log' => 'Неверное имя пользователя или пароль');
                    break;
                case 3:
                    $res->ERR = array('log' => 'Срок регистрации истек');
                    break;
                default:
                    $res->ERR = array('log' => 'Ошибка аутентификации');
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function LogoutAction($req) {
        Sun::model("Session")->Logout();
        header("Location: ?p=Index\\Enter"); //.$req->Referer()
    }


    //////////////////////////////////////////////////////////////
    /////////////////////////SEARCH///////////////////////////////
    //////////////////////////////////////////////////////////////
    public function SearchAction($req) {
        $edit = new Models\Edition();
        $res = new \Sun\Response();

        try {
            $type = $req->data['type'];
            $sort = $req->data['sort'];
            $num = $req->data['num'];
            $ops = explode(",", $req->data['ops']);
            $fields = explode(",", $req->data['fields']);
            $values = explode("[^&]", $req->data['values']);
            $id = $edit->CreateSearchReq($type, $fields, $values, $ops, $sort);

            $res->STAT = 'OK';
            $res->ID = $id;
        } catch (\Exception $e) {
            $res->STAT = 'ERR';
        }
        echo $res->ToJSON();
    }

    public function CatalogSearchAction($req) {
        $edit = new Models\Edition();

        try {
            $this->RenderViewScene('Index\\Catalog/SearchResult', $req->data);

        } catch (\Exception $e) {
            $res = new \Sun\Response();
            echo $res->ToJSON();
        }

    }



    public function SelItemAction($req) {
        Models\Search::SelItem($req->data['item_id']);
    }

    public function DeselItemAction($req) {
        Models\Search::DeselItem($req->data['item_id']);
    }

    public function GetSelItemsAction($req) {
        $items = Models\Search::GetSelItems();
        $res = implode(",", $items);
        echo json_encode($res);
    }

    public function ClearItemsAction($req) {
        Models\Search::ClearSelItems();
    }


    public function CheckOrder($req) {
        $edit = new Models\Edition();
        $user = new Models\User();
        try {
            $count = $edit->FindOrders($req->data['edit_id']);
            echo "{ COUNT: {$count} }";
        } catch (\Exception $e) {
            echo "{ ERR: 1 }";
        }
    }
}
